package com.solidtrust.app;

import java.io.File;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


@Component
@Transactional(readOnly = true)
public class ApplicationInitalizer implements ApplicationListener<ContextRefreshedEvent>{
	private static final Logger log4j = Logger.getLogger(ApplicationInitalizer.class);
	
	@PersistenceContext
	private EntityManager em;
	
	@Autowired
	private ConfigBean configBean;
	
	public void init() throws InterruptedException{
		configBean.loadConfig();
		initFS();
	}
	
	
	@Transactional(readOnly = false)
	private void initDB(){
		//home dir
		configBean.setValue(SolidtrustConstants.FILE_HOME, "f:\\car_fs");
		configBean.loadConfig();
	}
	
	
	private void initFS(){
		String dir = configBean.getValue(SolidtrustConstants.FILE_HOME);
		if(dir != null){
			log4j.info("File System: " + dir);
			FileSystemUtil.setHome(new File(dir));
		}
	}
	

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		try {
			init();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
